package net.zoneland.knowledge.service.impl;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import net.zoneland.knowledge.cache.RedisCacheUtil;
import net.zoneland.knowledge.constant.BizConstant;
import net.zoneland.knowledge.dao.FavoriteMapper;
import net.zoneland.knowledge.dao.PartyOrgMapper;
import net.zoneland.knowledge.dao.PartyUserMapper;
import net.zoneland.knowledge.dao.QaBankMapper;
import net.zoneland.knowledge.model.*;
import net.zoneland.knowledge.service.FavoriteService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * .
 *
 * @author: bcc
 * 2021/7/9
 */
@Service
public class FavoriteServiceImpl implements FavoriteService {

    @Autowired
    private FavoriteMapper favoriteMapper;

    @Autowired
    private PartyUserMapper partyUserMapper;

    @Autowired
    private PartyOrgMapper partyOrgMapper;

    @Autowired
    private QaBankMapper qaBankMapper;

    @Autowired
    private RedisCacheUtil redisCache;

    /**
     * 用户信息
     */
    private static final String USER_INFORMATION = "YHXX";

    /**
     * 支部信息
     */
    private static final String BRANCH_INFORMATION = "ZBXX";

    /**
     * 智查分类
     */
    private static final String ZC_TYPE = "ZC";

    /**
     * 智学分类
     */
    private static final String ZX_TYPE = "ZX";

    /**
     * 用户分组名
     */
    private static final String USER_GROUP_NAME = "userGroupName";

    /**
     * 支部分组名
     */
    private static final String BRANCH_GROUP_NAME = "branchGroupName";

    /**
     * 题库分组名
     */
    private static final String QUESTION_BANK_GROUP_NAME  = "questionBankGroupName";

    /**
     * 其它分组名
     */
    private static final String OTHER_GROUP_NAME = "otherGroupName";

    @Override
    public String addFavorite(final LoginUserPojo user, final String esQuestionId, final Integer type, final String category, final String titleType) {
        final String userID = user.getUserID();

        final FavoriteExample example = new FavoriteExample();
        example.createCriteria().andCreatorUidEqualTo(userID)
                .andEsQuestionIdEqualTo(esQuestionId)
                .andTitleTypeEqualTo(titleType);
        final List<Favorite> favorites = favoriteMapper.selectByExample(example);
        if(CollectionUtils.isNotEmpty(favorites)){
            final Favorite favorite = favorites.get(0);
            if(type == 1) {
                if (favorite.isEnabled()) {
                    return "已经收藏，不要重复收藏";
                } else {
                    favorite.setEnabled(true);
                    favorite.setUpdateTime(new Date());
                    favoriteMapper.updateByPrimaryKey(favorite);
                    redisCache.sadd(BizConstant.FAVORITE_CATE+userID,esQuestionId,0);
                }
            } else {
                if (favorite.isEnabled()) {
                    favorite.setEnabled(false);
                    favorite.setUpdateTime(new Date());
                    favoriteMapper.updateByPrimaryKey(favorite);
                    redisCache.sdel(BizConstant.FAVORITE_CATE+userID,esQuestionId);
                }
            }
        } else {
            if(type == 1) {
                Favorite favorite = new Favorite();
                favorite.setId(UUID.randomUUID().toString());
                favorite.setCreatorUid(userID);
                favorite.setCreatorName(user.getUserName());
                favorite.setEsQuestionId(esQuestionId);
                favorite.setEnabled(true);
                favorite.setCategory(category);
                favorite.setTitleType(titleType);
                favorite.setCreateTime(new Date());
                favorite.setUpdateTime(favorite.getCreateTime());
                favoriteMapper.insert(favorite);
                redisCache.sadd(BizConstant.FAVORITE_CATE+userID,esQuestionId,0);
            }
        }
        return null;
    }

    @Override
    public FavoriteVo searchFavorite(final LoginUserPojo user) {
        final List<Favorite> favorites = favoriteMapper.selectByCreatorUid(user.getUserID());

        final FavoriteVo favoriteVo = new FavoriteVo();

        Map<String, List<String>> map = favorites.stream().collect(Collectors.groupingBy(this::getColName, Collectors.mapping(Favorite::getEsQuestionId, Collectors.toList())));

        // 用户信息收藏列表
        favoriteVo.setPartyUsers(CollectionUtils.isNotEmpty(map.get(USER_GROUP_NAME)) ? partyUserMapper.getUserByYgIds(map.get(USER_GROUP_NAME)) : null);
        // 支部信息收藏列表
        favoriteVo.setPartyOrgs(CollectionUtils.isNotEmpty(map.get(BRANCH_GROUP_NAME)) ? partyOrgMapper.getOrgByUuids(map.get(BRANCH_GROUP_NAME)) : null);
        // 智学题库收藏列表
        favoriteVo.setQaBankWithBLOBs(CollectionUtils.isNotEmpty(map.get(QUESTION_BANK_GROUP_NAME)) ? qaBankMapper.selectByIds(map.get(QUESTION_BANK_GROUP_NAME)) : null);

        return favoriteVo;
    }

    @Override
    public boolean getFavoriteStatus(final QaResponse qaResponse, final LoginUserPojo user) {

        final HashMap map = (HashMap) qaResponse.getData();
        final String esQuestionId = String.valueOf(map.get("id"));
        final String userID = user.getUserID();

        final FavoriteExample example = new FavoriteExample();
        example.createCriteria().andCreatorUidEqualTo(userID)
                .andEsQuestionIdEqualTo(esQuestionId)
                .andTitleTypeEqualTo(ZX_TYPE)
                .andEnabledEqualTo(true);
        final List<Favorite> favorites = favoriteMapper.selectByExample(example);
        return CollectionUtils.isNotEmpty(favorites);
    }

    /**
     * 获取分组名称
     * @param favorite favorite
     * @return 分组名称
     */
    private String getColName(final Favorite favorite) {
        final String titleType = favorite.getTitleType();

        if (StringUtils.equals(titleType, ZC_TYPE)) {
            final String category = favorite.getCategory();

            if (StringUtils.equals(category, USER_INFORMATION)) {
                return USER_GROUP_NAME;
            }else if (StringUtils.equals(category, BRANCH_INFORMATION)) {
                return BRANCH_GROUP_NAME;
            }
        }else if (StringUtils.equals(titleType, ZX_TYPE)) {
            return QUESTION_BANK_GROUP_NAME;
        }
        return OTHER_GROUP_NAME;
    }

}
